import React, { Component } from 'react';
import { StyleSheet, View, Text, ScrollView, Button, NativeModules, RefreshControl } from 'react-native';
import { connect } from 'react-redux';
import { StackActions, NavigationActions } from 'react-navigation';
// import VideoPlayer from 'react-native-rn-videoplayer';
import {
  updateLoginStatus,
  updateChatListState
} from '../../redux/action';
import UserListView from "./View/UserListView";
import FilterTabs from "../../component/FilterTabs";
import { scaleSize } from '../../utils/ScreenUtils';
import ScrollViewPull from "../../component/ScrollViewPull";

class SectionWaterfall extends Component {
  constructor(props) {
    super(props);
    this.state = {
      num: 123,
      refreshing: false,
      tabIndex: 0,
      viewLength: 0
    };
  }

  componentDidMount() {
    // NativeModules.HideBottomNa.hide();
    this.resultView();
    let defaultItem = [
      {
        id: 1,
        name: '话题1',
        likeNumber: 0
      }, {
        id: 2,
        name: '话题2',
        likeNumber: 0
      }, {
        id: 3,
        name: '话题3',
        likeNumber: 0
      }, {
        id: 4,
        name: '话题4',
        likeNumber: 0
      }, {
        id: 9999,
        name: '第N话题',
        likeNumber: 0
      }]
    console.log('[Home props]', this.props);
    this.props.dispatch(updateChatListState({ list: defaultItem, command: 'updateList' }))
  }

  goto = () => {
    this.props.navigation.push('Home1', { routes: ['Home'] });
  };

  changeValue = () => {

  };

  loginOut = () => {
    this.props.dispatch(updateLoginStatus('login_no'));
    this.props.navigation.reset(
      [NavigationActions.navigate({ routeName: 'Login' })],
      0,
    );
  };

  sethookValue = () => {
    this.setState({
      num: '新值'
    })
  }

  btnItemEvent(index, likeNumber) {
    console.log('[btnItemEvent]')

  }

  refresPage = () => {

  }

  // 触底
  handleScrollEnd = () => {
    const { currentPage, lastPage, homeVideoCard } = this.props;
    console.log('[触底]')
    if (currentPage === lastPage) {
      // this.props.getVideoCard(undefined, currentPage + 1, homeVideoCard);
    }
  }

  // 开始下拉刷新
  handleRefreshBegin = () => {
    const { homeVideoCard } = this.props;
    console.log('[下拉]')
    // this.props.getChangeRefresh(true);
    // this.props.getSwiper();
    // this.props.getVideoCard(undefined, 1, homeVideoCard);
  }

  onPressHandler = (res) => {
    console.log('[onPressHandler]', res)
    this.state.viewLength = 0
    this.state.tabIndex = res.index
    this.resultView();
    this.setState({
      tabIndex: res.index
    })
  }

  resultView() {
    console.log('[resultView]', this.state.tabIndex)
    if (this.state.tabIndex == 0) {
      this.setState({
        viewLength: this.randomNum(10, 20)
      })
      return
    }
    if (this.state.tabIndex == 1) {
      this.setState({
        viewLength: this.randomNum(10, 20)
      })
    }
    if (this.state.tabIndex == 2) {
      setTimeout(() => {
        this.setState({
          viewLength: this.randomNum(10, 20)
        })
      }, 5000);
    }
  }

  onScroll = (res) => {
    this.state.scrollYNum = res.y;
  }

  render() {
    return (
      <View style={{ flex: 1 }}>
        {/* <ScrollView
          style={{ flex: 1 }}
          stickyHeaderIndices={[2]}
        >
          <Button title="Home1跳转" onPress={this.goto} />
          <View style={[marginT(20)]}>
            <Button title="修改值" onPress={this.changeValue} />
          </View>
          <View style={[marginT(20)]}>
            <Button title="退出登录" onPress={this.loginOut} />
          </View>
          <View style={[paddingT(200)]}>
            {this.renderChatList()}
            <Text>登录状态：{this.props.loginStatus}</Text>
          </View>
          
        </ScrollView> */}
        {this.renderView()}
      </View>
    );
  }

  renderView() {
    let tabs = [{ text: '选项1', status: 1 }, { text: '选项2', status: 1 }, { text: '选项3', status: 1 }]
    return (
      <ScrollViewPull
        ref={c => { this.ScrollViewPullRef = c }}
        style={{ flex: 1 }}
        stickyHeaderIndices={[2]}
        refreshing={this.state.refreshing}
        scrollEnd={() => this.handleScrollEnd()} // 触底回调
        refreshBegin={() => this.handleRefreshBegin()} // 开始下拉刷新回调
      >
        {/* <View style={{ flex: 1 }}> */}
        <View style={{ height: 300, backgroundColor: "#ddd" }}></View>
        <View style={{ height: 300, backgroundColor: "#999" }}></View>
        <FilterTabs
          tabs={tabs}
          activeIndex={this.state.tabIndex}
          tabsWrapStyle={{ backgroundColor: "#fff",height:scaleSize(100) }}
          itemStyle={{ width: scaleSize(240) }}
          onPressHandler={this.onPressHandler}
        />
        {this.renderSection()}
        {/* <View style={{ height: 400, backgroundColor: "#ddd" }}></View>
        <View style={{ height: 800, backgroundColor: "#ccc" }}></View> */}
        {/* </View> */}
      </ScrollViewPull>
    )
  }

  renderSection() {
    let itemView = [];
    // let list = this.randomNum(10, 20);
    const { viewLength } = this.state;

    if (this.state.tabIndex == 0) {
      for (let a = 0; a < viewLength; a++) {
        itemView.push(
          <>
            <View style={styles.itemBox}></View>
            <View style={styles.itemBox}></View>
          </>
        )
      }

      return (
        <View style={styles.itemWrap}>
          {itemView}
        </View>
      )
    }
    if (this.state.tabIndex == 1) {
      for (let a = 0; a < viewLength; a++) {
        itemView.push(
          <>
            <View style={[styles.itemBox, { backgroundColor: 'red' }]}></View>
            <View style={[styles.itemBox, { backgroundColor: 'red' }]}></View>
          </>
        )
      }
      return (
        <View style={styles.itemWrap}>
          {itemView}
        </View>
      )
    }
    if (this.state.tabIndex == 2) {
      if (viewLength > 0) {
        for (let a = 0; a < viewLength; a++) {
          itemView.push(
            <>
              <View style={[styles.itemBox, { backgroundColor: '#999' }]}></View>
              <View style={[styles.itemBox, { backgroundColor: '#999' }]}></View>
            </>
          )
        }
        return (
          <View style={styles.itemWrap}>
            {itemView}
          </View>
        )
      }

      let _resultScrollValue = this.ScrollViewPullRef.resultScrollValue()
      console.log('[ScrollViewPullRef]', _resultScrollValue)


      return (
        <View style={styles.itemWrap}>
          <View style={{width:'100%', height: parseInt(_resultScrollValue.y)+scaleSize(100), backgroundColor: "#000" }}></View>
        </View>
      )

    }

  }

  randomNum(minNum, maxNum) {
    switch (arguments.length) {
      case 1:
        return parseInt(Math.random() * minNum + 1, 10);
        break;
      case 2:
        return parseInt(Math.random() * (maxNum - minNum + 1) + minNum, 10);
        break;
      default:
        return 0;
        break;
    }
  }

  renderList() {
    const { user } = this.props;
    let listView = [];
    user.map((item, index) => {
      listView.push(
        <View key={index}>
          <View>
            <Text>姓名：{item.name}            点赞：{item.likeNumber}</Text>
            <Button title="点赞" onPress={() => this.btnItemEvent(index, item.likeNumber)} />
          </View>
        </View>
      );
    });
    return listView;
  }

  renderChatList() {
    const { updateChatListState } = this.props;
    let listView = [];
    updateChatListState.map((item, index) => {
      // listView.push(
      //   <View key={index}>
      //     <View>
      //       <Text>姓名：{item.name}            点赞：{item.likeNumber}</Text>
      //       <Button title="点赞" onPress={() => this.btnItemEvent(index, item.likeNumber)} />
      //     </View>
      //   </View>,
      // );
      listView.push(<UserListView key={index} item={item} index={index} navigation={this.props.navigation} />)
    });
    return listView;
  }
}

const mapStateToProps = (state) => ({
  user: state.user,
  loginStatus: state.loginStatus,
  updateChatListState: state.updateChatListState
});

export default connect(mapStateToProps)(SectionWaterfall);

const styles = StyleSheet.create({
  itemWrap: {
    flex: 1,
    flexDirection: 'row',
    alignItems: "center",
    justifyContent: 'space-between',
    marginLeft: scaleSize(10),
    marginRight: scaleSize(10),
    flexWrap: 'wrap'
  },
  itemBox: {
    width: scaleSize(300),
    height: scaleSize(400),
    backgroundColor: "#ccc",
    marginBottom: scaleSize(20)
  },
})
